<template>
  <view>
    <uni-section title="合同签署" type="line" sub-title="请确保姓名与手机号的注册姓名一致">
      <view class="example">
        <uni-forms ref="valiForm" :model-value="formData" :rules="formRules" label-position="top" label-width="150">
          <!--          <uni-forms-item label="身份证" required name="userIdCard">-->
          <!--            <uni-easyinput v-model="formData.userIdCard" placeholder="请输入签署人身份证">-->
          <!--              <template v-slot:right>-->
          <!--                <view style="padding: 5px" @tap="chooseAndUploadImage">-->
          <!--                  <uni-icons type="camera" size="25" color="#007aff"-->
          <!--                             style="margin-right: 10px"></uni-icons>-->
          <!--                </view>-->
          <!--              </template>-->
          <!--            </uni-easyinput>-->
          <!--          </uni-forms-item>-->
          <uni-forms-item label="姓名(签署人)" required name="username">
            <uni-easyinput v-model="formData.username" placeholder="请输入姓名"/>
          </uni-forms-item>
          <uni-forms-item label="手机号" required name="utelphone">
            <uni-easyinput v-model="formData.utelphone" placeholder="请输入签署人手机号">
            </uni-easyinput>
          </uni-forms-item>
          <!--          <uni-forms-item label="签署类型选择">-->
          <!--            <uni-data-checkbox v-model="choseContractType" :localdata="contractTypeLocations"/>-->
          <!--          </uni-forms-item>-->
          <!--          <uni-forms-item label="进入方式">-->
          <!--            <uni-data-checkbox v-model="formData.notifyType" :localdata="noticeLocations"/>-->
          <!--          </uni-forms-item>-->
          <view class="db">
            <!--            <view class="xieyi" style="line-height: 39upx;">-->
            <!--              <view class="xieyicaozuo" style="display: flex;align-items: center;">-->
            <!--                <checkbox-group @change="selfChangde()">-->
            <!--                  <checkbox :value="xieyiflag" color="#1aad19" style="transform:scale(0.7);"/>-->
            <!--                </checkbox-group>-->
            <!--                <text style="font-weight: 700;">已阅读并同意以下内容:</text>-->
            <!--              </view>-->
            <!--              <view class="xieyitext">-->
            <!--                已知晓录入的签署人员身份证件信息，将用于预订租车产品，并在使用时根据有关法律规定进行查验或留存，录入信息真实有效。系统将通过加密等方式保护此信息，并在预订过程中提供给实际提供服务的租车公司。-->
            <!--              </view>-->
            <!--            </view>-->
            <button type="primary" style="width: 100%; margin-top: 20upx;" @tap="verification">合同签署</button>
          </view>
        </uni-forms>

      </view>
    </uni-section>
    <uni-popup type="bottom" ref="codePopup">
      <view class="example" style="height: 70vh;">
        <view class="title">输入短信验证码</view>
        <view class="explain">验证码已发送至{{ getCodeItPhone() }}，请在下方输入框中输入6位数字验证码
        </view>
        <view class="verificationBox">
          <myp-one :auto-focus="true" type="box" maxlength="6" @finish="submitData"/>
          <view @click="sendPhoneCode">
            <text class="explain" v-if="readSeconds">{{ readSeconds }}秒后重新发送</text>
            <text class="send-code" v-else>重新发送</text>
          </view>
        </view>
      </view>
    </uni-popup>
    <uni-popup ref="message" type="message">
      <uni-popup-message type="info" :message="msg" :duration="5000"></uni-popup-message>
    </uni-popup>
  </view>
</template>

<script>
import {sha256} from "js-sha256";
import {pathToBase64} from "image-tools";
import {mapState} from 'vuex'
import {sendMsg, verificationCode} from "@/utils/api/basics";
import {createSignContractUrl, initiateContract} from "@/utils/api/order";
import {getordervehorder} from "@/utils/new_file";
import {txAppId, uploadIdCardAppId, uploadIdCardSppSecret} from "@/utils/config";


export default {
  data() {
    return {
      xieyiflag: false,
      phoneCode: '',
      contractTypeLocations: [
        {
          text: '个人',
          value: 0
        }, {
          text: '企业',
          value: 1,
          disabled: true
        }],
      noticeLocations: [
        {
          text: '进入签署',
          value: 'NONE',
        },
        {
          text: '短信',
          value: 'SMS'
        }],
      msg: '',
      orderNum: '',
      choseContractType: 0,
      formData: {
        username: '',
        userIdCard: '',
        utelphone: '',
        id: '',
        orderNum: '',
        merUnitId: '',
        notifyType: 'NONE',
        txFlowId: null
      },
      formRules: {
        username: {
          rules: [{required: true, errorMessage: '请输入姓名'}]
        },
        utelphone: {
          rules: [{required: true, errorMessage: '请输入手机号码'},
            {
              format: 'number',
            },
            {
              pattern: "^1[3456789]\\d{9}$",
              errorMessage: '手机号码不合法，请重新输入'
            }]
        },
        userIdCard: {
          rules: [{
            required: true,
            errorMessage: '请输入正确的身份证号'
          }, {pattern: '(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)', errorMessage: '请输入正确的身份证号'}]
        }
      }
    };
  },
  computed: {
    ...mapState(['readSeconds'])
  },
  methods: {
    jumpPending() {
      createSignContractUrl(this.formData).then(res => {
        if (res.data.code == 200) {
          wx.navigateToMiniProgram({
            appId: txAppId,
            path: res.data.data.signUrl
          })
          uni.hideLoading()
        }
      })
    },
    submitData(code) {
      uni.showLoading()
      verificationCode({
        phone: this.formData.utelphone,
        verificationCode: code
      }).then(res => {
        if (res.data.code == 200) {
          this.sendInitiateContract()
        } else {
          uni.showToast({
            title: res.data.msg,
            icon: "none"
          })
        }
      })

      console.log(code)
      console.log(this.formData)
    },
    getCodeItPhone() {
      return this.formData.utelphone.slice(-4)
    },
    chooseAndUploadImage() {
      // 身份证识别
      let what = this
      let timestamp = Date.now();
      let sign = sha256(uploadIdCardAppId + uploadIdCardSppSecret + timestamp)
      uni.chooseImage({
        count: 1, // 选择的图片数量
        success: (chooseImageRes) => {
          const tempFilePaths = chooseImageRes.tempFilePaths;
          // 图片转化为base64格式
          pathToBase64(tempFilePaths[0]).then(data => {
            console.log(data);
            uni.request({
              header: {
                'Content-Type': 'application/x-www-form-urlencoded'
              },
              url: 'https://api.jumdata.com/ocr/idcard-v1',
              method: 'POST',
              data: {
                appId: uploadIdCardAppId,
                base64: data,
                timestamp: timestamp,
                sign: sign
              },
              success: function (res) {
                what.formData.userIdCard = res.data.data.info.number
                what.formData.username = res.data.data.info.name
              },
              fail(err) {
                console.log(err);
              }
            })
          })
        }
      });
    },
    selfChangde() {
      this.xieyiflag = !this.xieyiflag
    },
    // 修改用户信息
    changeUserInfo() {
      let useinfo = uni.getStorageSync('useinfo')
      useinfo.userName = this.formData.username
      uni.setStorageSync('useinfo', useinfo)
    },
    sendInitiateContract() {
      uni.showLoading()
      initiateContract(this.formData).then(response => {
        if (response.data.code == 200) {
          this.changeUserInfo()
          this.formData.txFlowId = response.data.data
          setTimeout(() => {
            this.jumpPending()
          }, 1000)
          // 进行消息提示
          if (response.data.msg) {
            this.msg = response.data.msg
            this.$refs.message.open()
          }
          this.$refs.codePopup.close()
        } else {
          uni.showToast({
            title: response.data.msg,
            icon: 'none',
            duration: 5000
          })
        }
      }).catch(err => {
        uni.hideLoading()
        console.error(err)
      })
    },
    sendPhoneCode() {
      if (this.readSeconds) {
        return
      }
      sendMsg({phone: this.formData.utelphone})
      this.$store.commit('setReadSeconds', 60)
      let a = setInterval(() => {
        if (this.readSeconds <= 0) {
          this.$store.commit('setReadSeconds', undefined)
          clearInterval(a)
        } else {
          this.$store.commit('setReadSeconds', this.readSeconds - 1)
        }
      }, 1000)
    },
    verification() {
      // if (!this.xieyiflag) {
      //   uni.showToast({
      //     title: '请先勾选同意再发起',
      //     icon: "none"
      //   })
      //   return
      // }
      this.$refs.valiForm.validate().then(res => {
        console.log(this.formData)
        // this.$refs.codePopup.open()
        // this.sendPhoneCode()
        this.sendInitiateContract()
      }).catch(err => {
        console.log('表单错误信息', err)
      })
    }
  },
  onShow() {
    getordervehorder(this.orderNum).then(data => {
      if (data.data.code == 200) {
        console.log(data.data.data)
        if (data.data.data.txFlowStatus) {
          //uni.navigateBack()
        }
        this.formData = data.data.data
        if (this.formData.username == '微信用户') {

          this.formData.username = ''
        }
        this.formData.userIdCard = ''
        this.formData.notifyType = 'NONE'
        if (this.formData.txFlowStatus) {
          uni.navigateBack()
        }
      }
    })
  },
  onLoad(opt) {
    this.orderNum = opt.orderNum
  },
}
</script>

<style lang="scss">
.example {
  padding: 15px;
  background-color: #fff;
}

.db {
  width: 100%;
  font-size: 24upx;
  padding: 20upx 30upx;
}

.title {
  font-size: 20px;
  font-weight: bold;
}

.explain {
  font-size: 14px;
  color: #939393;
}

.verificationBox {
  margin-top: 40upx;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 40upx;
}

.send-code {
  color: #007aff;
  font-size: 14px;
}

</style>
